package com.own.component.common.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * IpUtil
 *
 * @author chenxueli
 * @date 2022-06-19 20:44:00
 */
public class IpUtil {

    private static final String UNKNOWN = "unknown";

    private static final List<String> HEADER_LIST = new ArrayList<>() {{
        add("X-Original-Forwarded-For");
        add("X-Forwarded-For");
        add("x-forwarded-for");
        add("Proxy-Client-IP");
        add("WL-Proxy-Client-IP");
        add("HTTP_CLIENT_IP");
        add("HTTP_X_FORWARDED_FOR");
        add("X-Real-IP");
    }};

    /**
     * 获取ip信息
     *
     * @param request 请求内容
     * @return ip信息
     */
    public static String getIpAddress(HttpServletRequest request) {
        var ip = get(request);
        // 还是不能获取到，最后再通过request.getRemoteAddr();获取
        if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            return request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 获取ip信息
     *
     * @param request 请求内容
     * @return ip信息
     */
    private static String get(HttpServletRequest request) {
        for (var header : HEADER_LIST) {
            var ip = request.getHeader(header);
            if (StringUtils.isNotBlank(ip) && !UNKNOWN.equalsIgnoreCase(ip)) {
                return ip;
            }
        }
        return null;
    }

}
